package com.gzc.just.play.last.war.common.message.handler;

import com.gzc.just.play.last.war.common.battle.BattleManager;
import com.gzc.just.play.last.war.common.model.Position;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Player movement message handler
 */
@Component
public class PlayerMoveHandler implements MessageHandlerInterface {

    private static final Logger log = LoggerFactory.getLogger(PlayerMoveHandler.class);

    private final BattleManager battleManager;
    private final ObjectMapper objectMapper;
    
    public PlayerMoveHandler(BattleManager battleManager, ObjectMapper objectMapper) {
        this.battleManager = battleManager;
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(Long playerId, Object messageData) {
        try {
            // Parse movement data
            Map<String, Object> moveData = objectMapper.convertValue(messageData, Map.class);
            
            double x = (double) moveData.get("x");
            double y = (double) moveData.get("y");
            double z = (double) moveData.getOrDefault("z", 0.0);
            
            Position newPosition = new Position(x, y, z);
            
            // Process movement in battle
            if (battleManager.isPlayerInBattle(playerId)) {
                // Handle movement in battle
                processBattleMove(playerId, newPosition);
            } else {
                // Handle normal movement
                processNormalMove(playerId, newPosition);
            }
            
            log.debug("Player {} moved to position: {}", playerId, newPosition);
        } catch (Exception e) {
            log.error("Error processing player move for player: {}", playerId, e);
        }
    }
    
    /**
     * Process movement in battle
     * @param playerId Player ID
     * @param position New position
     */
    private void processBattleMove(Long playerId, Position position) {
        // Handle movement in battle with restrictions
        // Implementation depends on specific game rules
        log.debug("Player {} moved in battle to position: {}", playerId, position);
    }
    
    /**
     * Process normal movement
     * @param playerId Player ID
     * @param position New position
     */
    private void processNormalMove(Long playerId, Position position) {
        // Handle normal movement
        // Implementation depends on specific game rules
        log.debug("Player {} moved normally to position: {}", playerId, position);
    }
}